<template>
  <div>
    <slot :loading="loading" :click="onClick" :upload="onUpload"></slot>
    <input ref="input" type="file" style="display:none" @change="onUpload" />
  </div>
</template>
<script>
import { ref } from 'vue'
import { upload } from '@/api/manage'

export default {
  props: ['modelValue'],
  setup(props, { emit }) {
    // 控件
    const input = ref(null)

    // 加载
    const loading = ref(false)

    // 上传
    const onUpload = (e) => {
      const file = e.target.files;

      // 取单文件
      if(file.length > 0) {
        loading.value = true
        upload('image', file[0]).then(res => {
          emit('update:modelValue', res.url)
        }).finally(() => {
          loading.value = false
        })
      }
    }

    // 选择文件
    const onClick = () => {
      input.value.click()
    }

    return {
      input,
      loading,
      onClick,
      onUpload
    }
  }
}
</script>